package com.luoxiang.socialandroid.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.luoxiang.lib_common.bean.NumberBean
import com.luoxiang.lib_common.common.Constants
import com.luoxiang.lib_common.utils.NetUtils
import com.luoxiang.socialandroid.R
import com.luoxiang.socialandroid.activity.DetailsActivity
import com.luoxiang.socialandroid.adapter.InviteListAdapter
import com.luoxiang.socialandroid.adapter.InviteListDayAdapter
import com.luoxiang.socialandroid.base.LazyLoadFragment
import com.luoxiang.socialandroid.bean.ListBean
import com.luoxiang.socialandroid.bean.ListData
import com.luoxiang.socialandroid.bean.ListDetail
import com.luoxiang.socialandroid.bean.RewardBean
import com.luoxiang.socialandroid.common.Constants.MmkvConst.USERID
import com.luoxiang.socialandroid.databinding.FragmentInviteSubBinding
import com.luoxiang.socialandroid.utils.AESUtil
import com.luoxiang.socialandroid.utils.MmkvUtil
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

/**
 * Author: fuxinbo

 * Date: 2023/2/9

 * Description:
 */
class InviteSubFragment : LazyLoadFragment() {

    private lateinit var binding: FragmentInviteSubBinding

    private var mAdapter: BaseQuickAdapter<ListDetail, BaseViewHolder>? = null

    /**
     * 当前榜单类型(0：上周榜，1：日榜，2：周榜)
     */
    private var mCurrentListType: Int = 0

    private val map: HashMap<Int, ListDetail> = hashMapOf()

    override fun setContentView(): Int = R.layout.fragment_invite_sub

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentInviteSubBinding.inflate(layoutInflater)
        super.onCreateView(inflater, container, savedInstanceState)
        return binding.root
    }

    override fun initView() {
        mCurrentListType = arguments?.getInt(PAGE_TYPE, 0) ?: 0
        binding.ivState.setOnClickListener {
            if (map[1]?.status == 0 || MmkvUtil.decodeInt(com.luoxiang.socialandroid.common.Constants.MmkvConst.ACCID)
                    ?.toLong() != map[1]?.userId
            ) return@setOnClickListener
            claimReward(map[1]?.id?.toString() ?: "", img = binding.ivState)
        }
        binding.ivTwoState.setOnClickListener {
            if (map[2]?.status == 0 || MmkvUtil.decodeInt(com.luoxiang.socialandroid.common.Constants.MmkvConst.ACCID)
                    ?.toLong() != map[2]?.userId
            ) return@setOnClickListener
            claimReward(map[2]?.id?.toString() ?: "", img = binding.ivTwoState)
        }
        binding.ivThreeState.setOnClickListener {
            if (map[3]?.status == 0 || MmkvUtil.decodeInt(com.luoxiang.socialandroid.common.Constants.MmkvConst.ACCID)
                    ?.toLong() != map[3]?.userId
            ) return@setOnClickListener
            claimReward(map[3]?.id?.toString() ?: "", img = binding.ivThreeState)
        }
        initAdapter()
    }

    override fun lazyLoad() {}

    override fun onResume() {
        super.onResume()
        getInviteListData()
    }

    private fun initAdapter() {
        mAdapter = if (mCurrentListType == 1 || mCurrentListType == 2) {
            InviteListDayAdapter()
        } else {
            InviteListAdapter()
        }
        binding.recyclerList.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            setHasFixedSize(true)
        }
        mAdapter?.addChildClickViewIds(R.id.textReceive1)
        mAdapter?.setOnItemChildClickListener { adapter, view, position ->
            (adapter.data[position] as? ListDetail)?.let {
                if (it.status == 0 || MmkvUtil.decodeInt(USERID)?.toLong() != it.userId) return@let
                claimReward(it.id.toString(), isList = true, position = position)
            }
        }
    }

    private fun getInviteListData() {
        NetUtils.getInstance().apiService.getInviteListData(
            Constants.MmkvConst.EXTRA,
            MmkvUtil.decodeString(Constants.MmkvConst.TOKEN),
            4,
            when (mCurrentListType) {
                0 -> 3
                1 -> 0
                2 -> 1
                else -> 3
            }
        ).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NumberBean> {
                override fun onSubscribe(d: Disposable?) {}

                override fun onError(e: Throwable?) {}

                override fun onComplete() {}

                override fun onNext(value: NumberBean?) {
                    val data = value?.data
                    var decryptStr: String? = null
                    try {
                        decryptStr = AESUtil.aesDecryptString(data, Constants.MmkvConst.KEY)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    LogUtils.i("decryptStr10", decryptStr)
                    val listData = Gson().fromJson<ListBean>(
                        decryptStr,
                        object : TypeToken<ListBean>() {}.type
                    )
                    if (listData.data != null) {
                        setTopThreeData(listData.data)
                        setListData(listData.data)
                    }
                }
            })
    }

    private fun setTopThreeData(data: ListData) {
        if (data.tops.isEmpty()) {
            return
        }
        data.tops[0].let {
            binding.tvOneUserName.text = it.name
            map[1] = it
            binding.tvReward.text = if (mCurrentListType == 1 || mCurrentListType == 2) {
                binding.ivState.visibility = View.GONE
                "邀请首充：${it.num}人"
            } else {
                binding.ivState.visibility = View.VISIBLE
                "奖励：${it.reward}积分"
            }
            setRewardState(binding.ivState, it.status)
            Glide.with(contentView).load(domain + it.icon)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .into(binding.imageUserOne)
        }
        data.tops.remove(data.tops[0])

        if (data.tops.isEmpty()) {
            return
        }
        data.tops[0].let {
            map[2] = it
            binding.tvTwoUserName.text = it.name
            binding.tvTwoReward.text = if (mCurrentListType == 1 || mCurrentListType == 2) {
                binding.ivTwoState.visibility = View.GONE
                "邀请首充：${it.num}人"
            } else {
                binding.ivTwoState.visibility = View.VISIBLE
                "奖励：${it.reward}积分"
            }
            setRewardState(binding.ivTwoState, it.status)
            Glide.with(contentView).load(domain + it.icon)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .into(binding.imageUserTwo)
        }
        data.tops.remove(data.tops[0])

        if (data.tops.isEmpty()) {
            return
        }
        data.tops[0].let {
            map[3] = it
            binding.tvThreeUserName.text = it.name
            binding.tvThreeReward.text = if (mCurrentListType == 1 || mCurrentListType == 2) {
                binding.ivThreeState.visibility = View.GONE
                "邀请首充：${it.num}人"
            } else {
                binding.ivThreeState.visibility = View.VISIBLE
                "奖励：${it.reward}积分"
            }
            setRewardState(binding.ivThreeState, it.status)
            Glide.with(contentView).load(domain + it.icon)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .into(binding.imageUserThree)
        }
        data.tops.remove(data.tops[0])
    }

    private fun setListData(data: ListData) {
        if (data.tops.isEmpty()) return
        mAdapter?.setList(data.tops)
    }

    private fun setRewardState(img: TextView?, status: Int? = 1) {
        img?.text = if (status == 0) "已领取" else "未领取"
        img?.setBackgroundResource(if (status == 0) R.drawable.bg_list_item_receive else R.drawable.bg_list_item_no_receive)
        img?.setTextColor(
            if (status == 0) ContextCompat.getColor(
                requireContext(),
                R.color.black
            ) else ContextCompat.getColor(requireContext(), R.color.white)
        )
    }

    private fun claimReward(
        id: String, img: TextView? = null, isList: Boolean = false, position: Int = 0
    ) {
        NetUtils.getInstance().apiService.claimReward(
            Constants.MmkvConst.EXTRA,
            MmkvUtil.decodeString(Constants.MmkvConst.TOKEN),
            id
        ).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NumberBean> {
                override fun onSubscribe(d: Disposable?) {}

                override fun onError(e: Throwable?) {}

                override fun onComplete() {}

                override fun onNext(value: NumberBean?) {
                    val data = value?.data
                    var decryptStr: String? = null
                    try {
                        decryptStr = AESUtil.aesDecryptString(data, Constants.MmkvConst.KEY)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    val bean = Gson().fromJson<RewardBean>(
                        decryptStr,
                        object : TypeToken<RewardBean>() {}.type
                    )
                    if (bean.code == 1) {
                        Toast.makeText(context, bean.msg, Toast.LENGTH_SHORT).show()
                        return
                    }
                    if (isList) {
                        (mAdapter!!.data[position] as? ListDetail)?.let {
                            it.status = 0
                        }
                        mAdapter?.notifyItemChanged(position)
                    } else {
                        setRewardState(img, 0)
                    }
                }
            })
    }

    private fun toUserDetailPage(userId: Int) {
        startActivity(Intent(requireContext(), DetailsActivity::class.java).apply {
            putExtra("userid", userId)
        })
    }
}